package com.xq.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xq.entity.CityInfo;
import com.xq.mapper.CityInfoMapper;
import com.xq.vo.CityResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class CityServiceImpl {


    @Autowired
    private CityInfoMapper mapper;

    //@PostConstruct
    public void init(){

         int count = mapper.selectCount(null);
         if(count>0){
             return;
         }

        String str = HttpUtil.get("https://mxnzp.com/api/address/list?app_id=pnjgrriit6wghnlo&app_secret=YXBoenBlWnZmanhLWTRxenNCL1p3Zz09");
        System.out.println(str);
        if(StringUtils.isBlank(str)){
            return;
        }
        CityResult result = JSONObject.parseObject(str, CityResult.class);
        if(result.getCode()!=1){
            return;
        }
        result.getData().forEach(c->{
            CityInfo cityInfo = new CityInfo();
            cityInfo.setPid(0L);
            cityInfo.setCode(c.getCode());
            cityInfo.setpCode("0");
            cityInfo.setName(c.getName());
            cityInfo.setSub(1);
            mapper.insertUseGeneratedKeys(cityInfo);
            c.getPchilds().forEach(b->{
                CityInfo cityInfo2 = new CityInfo();
                cityInfo2.setPid(cityInfo.getId());
                cityInfo2.setpCode(c.getCode());
                cityInfo2.setCode(b.getCode());
                cityInfo2.setName(b.getName());
                cityInfo2.setSub(2);
                mapper.insertSelective(cityInfo2);
                b.getCchilds().forEach(d->{
                    CityInfo cityInfo3 = new CityInfo();
                    cityInfo3.setPid(cityInfo2.getId());
                    cityInfo3.setpCode(b.getCode());
                    cityInfo3.setCode(d.getCode());
                    cityInfo3.setName(d.getName());
                    cityInfo3.setSub(3);
                    mapper.insertSelective(cityInfo3);
                });
            });
        });

    }
}
